package JAVA300.第十一章多线程;

/**
 * 死锁案例
 * 一个人拿镜子一个人拿口红
 */

public class thread_17_deadLock {
    public static void main(String[] args) {

        MakeUp g1 = new MakeUp(0,"wang");
        MakeUp g2 = new MakeUp(1,"li");

        g1.start();
        g2.start();


    }
}

class Lipstick{

}

class Mirror{

}

class  MakeUp extends Thread{

    static Lipstick lipstick = new Lipstick();//一面镜子 一个口红 所以家静态
    static Mirror mirror = new Mirror();

    int choice;//0 拿口红
    String girlname;

    public MakeUp(int choice,String girlname) {
        this.choice = choice;
        this.girlname = girlname;
    }

    @Override
    public void run() {

        //化妆
        makeup();

    }

    //拿到对方的锁 容易造成死锁
    private void makeup()  {
        if (choice ==0){
            synchronized (lipstick){//获得口红的锁
                System.out.println(this.girlname +"获得口红");
                //1s后想要镜子
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                /*synchronized (mirror){
                    System.out.println(this.girlname +"照镜子");
                }*/

            }
            //解决死锁--不要锁套锁
            synchronized (mirror){
                System.out.println(this.girlname +"照镜子");
            }
        }else {


            synchronized (mirror){//获得镜子的锁
                System.out.println(this.girlname +"获得镜子");
                //2s后想要镜子
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (lipstick){
                    System.out.println(this.girlname +"照镜子");
                }

            }
        }

    }
}
